import json
import hashlib
import os

USER_FILE = 'users.json'


def load_users():
    if os.path.exists(USER_FILE):
        try:
            with open(USER_FILE, 'r') as f:
                return json.load(f)
        except json.JSONDecodeError:
            # 处理空文件或无效JSON的情况
            return {}
    return {}


def save_users(users):
    with open(USER_FILE, 'w') as f:
        json.dump(users, f, indent=2)


def register(username, password):
    users = load_users()
    if username in users:
        return False  # 用户名已存在

    hashed_pw = hashlib.sha256(password.encode()).hexdigest()
    users[username] = hashed_pw
    save_users(users)
    return True


def login(username, password):
    users = load_users()
    hashed_pw = hashlib.sha256(password.encode()).hexdigest()

    if username in users and users[username] == hashed_pw:
        return True  # 登录成功

    return False  # 登录失败